<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <p>vue中数组和对象的更新问题</p>
    <p>一.数组不能正常更新</p>
    <p>1.通过下标修改数组的一整项</p>
    <p v-for="phone in arr1">{{phone.name}}-￥{{phone.price}}</p>
    <button @click="changeItem">修改数组的一整项</button>
    <p>2.通过数组长度修改数组</p>
    <p v-for="phone in arr1">{{phone.name}}-￥{{phone.price}}</p>
    <button @click="changeLength">修改数组的长度</button>
    <hr>
    <p>一.对象不能正常更新</p>
    <p>1.新增对象属性</p>
    <p v-for="(val,key,index) in obj1">
      <span>{{index + 1}}.{{key}}:{{val}}</span>
    </p>
    <button @click="getJob">拿到offer</button>
    <p>1.删除对象属性</p>
    <p v-for="(val,key,index) in obj1">
      <span>{{index + 1}}.{{key}}:{{val}}</span>
    </p>
    <button @click="lossName">无名氏</button>
  </div>
  <script src="./vue.js"></script>
  <script>
    let vm = new Vue({
      el: '#app',
      data: {
        arr1: [
          {name: 'iphone 12', price: 6999},
          {name: 'mi 11', price: 3999},
          {name: 'huawei p40', price: 4999},
        ],
        obj1: {
          name: 'Jack',
          age: 18,
          sex: 'male'
        }
      },
      created() {
        console.log(666);
        let userData = JSON.parse(localStorage.getItem('todoThings')) || [];
        console.log(userData);
      },
      methods: {
        changeItem() {
          // 错误的方式
          // this.arr1[0] = {name: 'iphone 11', price: 4499};
          // 正确方式1
          // this.arr1.splice(0, 1, {name: 'iphone 11', price: 4499});
          // 正确方式2
          this.$set(this.arr1, 0, {name: 'iphone 11', price: 4499})
          // Vue.set(this.arr1, 0, {name: 'iphone 11', price: 4499})
        },
        changeLength() {
          // 错误方式1
          // this.arr1.length = 1;
          // 正确方式
          this.arr1.splice(0, 1)
        },
        getJob() {
          // 错误的方式
          // this.obj1.job = 'fornt end'
          // 正确的方式
          // this.$set(this.obj1, 'job', 'fornt end');
          Vue.set(this.obj1, 'job', 'fornt end');
        },
        lossName() {
          // 错误的方式
          // delete this.obj1.name;
          // 正确的方式
          // this.$delete(this.obj1, 'name');
          Vue.delete(this.obj1, 'name');
        }
      },
    })
  </script>
</body>
</html>